<template>
    <SysDialog :title="dialog.title" :visible="dialog.visible" :width="dialog.width" :height="dialog.height"
        @onClose="onClose" @onConfirm="commit">
        <template v-slot:content>
            <el-form :model="addModel" ref="addFormRef" label-width="90px" :inline="false" size="default">
                <el-row :gutter="20">
                    <el-col :span="8" :offset="0">
                        <el-form-item prop="mingCheng" label="名称">
                            <el-input v-model="addModel.mingCheng"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" :offset="0">
                        <el-form-item prop="xingHao" label="型号">
                            <el-input v-model="addModel.xingHao"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="8" :offset="0">
                        <el-form-item prop="chiCun" label="尺寸">
                            <el-input v-model="addModel.chiCun"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" :offset="0">
                        <el-form-item prop="zhongLiang" label="重量">
                            <el-input v-model="addModel.zhongLiang"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="8" :offset="0">
                        <el-form-item prop="jiaoHuoZhouQi" label="交货周期">
                            <el-input v-model="addModel.jiaoHuoZhouQi"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" :offset="0">
                        <el-form-item prop="fuJian" label="附件">
                            <div>
                                <input type="file" :icon="Plus" @change="handleFileChange($event)" />
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item prop="beiZhu" label="备注">
                    <textarea rows="5" cols="100" v-model="addModel.beiZhu"></textarea>
                </el-form-item>

            </el-form>

        </template>
    </SysDialog>
</template>

<script setup lang="ts">

import SysDialog from '@/components/SysDialog.vue'
import useDialog from '@/hooks/useDialog';
import { nextTick, reactive, ref } from 'vue';
import { ProductModel } from '@/api/product/ProductModel';
import { ElMessage, FormInstance } from 'element-plus';
import { addUserApi, editUserApi, getListApi } from '@/api/product';
import { EditType, Title } from '@/type/BaseType';
import { Plus } from '@element-plus/icons-vue';

const { dialog, onClose, onConfirm, onShow } = useDialog()    //弹框属性

const show = (type: string, row?: ProductModel) => {//显示弹窗
    
    type == EditType.ADD ? dialog.title = Title.ADD : dialog.title = Title.EDIT
    dialog.height = 500
    dialog.width = 1000
    dialog.visible = true

    if (row) {
        nextTick(() => {
            Object.assign(addModel, row)
            console.log('addModel:', addModel);
        })
    }

    addFormRef.value?.resetFields()

    addModel.type = type;
};


defineExpose({
    show
})


const addModel = reactive<ProductModel>({
    type: '',
    id: '',
    mingCheng: '',
    zhongLiang: '',
    xingHao: '',
    jiaoHuoZhouQi: '',
    chiCun: '',
    fuJian: '',
    beiZhu: '',
    fileUrl:'',
})


const addFormRef = ref<FormInstance>()


const emists = defineEmits(['onFresh'])  


const commit = () => {
    addFormRef.value?.validate(async (valid) => {
        if (valid) {
            let res = null;
            if (addModel.type == EditType.ADD) {
                res = await addUserApi(addModel);
            } else {
                res = await editUserApi(addModel);
            }
            console.log(res)
            if (res && res.code == 200) {
                ElMessage.success(res.msg)
                emists('onFresh')
                onClose()
            }
        }
    })
}

//上传文件

const selectedFiles = ref<File | null>(null);

const handleFileChange = async (event: Event) => {
    const target = event.target as HTMLInputElement;
    if (target.files && target.files.length > 0) {
        const file = target.files[0];
        selectedFiles.value = file;
        addModel.fuJian = file.name; 
     
        // 直接调用上传函数
        await uploadFile();
    }
};

const uploadFile = async () => {
    const file = selectedFiles.value;
    if (!file) {
        alert('请选择一个文件');
        return;
    }

    const formData = new FormData();
    formData.append('file', file);

    try {
        const response = await fetch('http://localhost:8080/api/api/upload', {
            method: 'POST',
            body: formData,
        });

        const result = await response.json();
        console.log('上传成功结果Result:', result.data);
        addModel.fileUrl = result.data;
    } catch (error) {
        console.error('上传失败:', error);
    }
};
</script>
<style scoped></style>